package service

import (
	"errors"
	"gorm.io/gorm/clause"
	"wit-admin-go/business/dto"
	"wit-admin-go/business/model"
	"wit-admin-go/system/utils"
)

type testService struct{}

var TestService = new(testService)

// PostCreateTest  创建测试
func (us *testService) PostCreateTest(test dto.Test) (err error) {
	return utils.DB.Create(&test).Error
}

// PutUpdateTest 修改测试
func (us *testService) PutUpdateTest(test dto.Test) (err error) {
	_, errN := us.GetTestById(test.Id)
	if errN != nil {
		return errN
	}
	tests := new(model.Test)
	return utils.DB.Model(&tests).Where("id = ?", test.Id).Updates(test).Error
}

// GetTestById 通过ID查询数据
func (us *testService) GetTestById(id string) (test model.Test, err error) {
	err = utils.DB.First(&test, "id = ?", id).Error
	if err != nil {
		return test, errors.New("数据没找到")
	}
	return test, err
}

// GetTestList 获取所有数据
func (us *testService) GetTestList(page *dto.TestPage) (*[]model.Test, int64) {
	test := new([]model.Test)
	db := utils.DB.Preload(clause.Associations)
	if page.Name != "" {
		db = db.Where("name = ?", page.Name)
	}
	total := db.Scopes(utils.Paginate(page.PageNum, page.PageSize)).Find(&test).RowsAffected
	if total > 0 {
		return test, total
	} else {
		return nil, 0
	}
}

// DelTest 删除数据
func (us *testService) DelTest(id string, userId string) (err error) {
	test, errN := us.GetTestById(id)
	if errN != nil {
		return errN
	}
	test.DeleteId = userId
	err = utils.DB.Delete(&test, "id = ?", id).Error
	return err
}

// RemoveTest 永久删除数据
func (us *testService) RemoveTest(id string) (err error) {
	test := new(model.Test)
	err = utils.DB.Unscoped().Delete(&test, "id = ?", id).Error
	return err
}
